package com.keliangliu.demo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.ReferenceCountUtil;

public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {


    private NettyClient nettyClient = new NettyClient();
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new ClientHandler());
    }


    class ClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            // channel 第一次连上可用，写出一个字符串
            ByteBuf buf = Unpooled.copiedBuffer("hello".getBytes());
            ctx.writeAndFlush(buf); // 自动释放资源
        }
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf=null;
            try {
                buf = (ByteBuf)msg;
                System.out.println(buf);
            }finally {
                if (buf != null) {
                    ReferenceCountUtil.release(buf);
                }
            }
        }


        /**
         * 发现服务端连接问题，就会触发
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("开始重新连接");

            nettyClient.connect();
            ctx.fireChannelActive();
        }

        /**
         *
         * @param ctx
         * @param cause
         * @throws Exception
         */
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

            super.exceptionCaught(ctx, cause);
        }
    }
}
